<template>
  <!-- 校招岗位行业薪酬水平 -->
  <div class="content">
    <span class="tinyTitle">
      <div class="titleFlag"></div>
      {{ "行业薪酬水平" }}
    </span>
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            :clearable="false"
            size="small"
            type="monthrange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="行业名称：">
          <IndustryCheckbox
            :limitNum="1"
            ref="regionRef"
            :selectBetweenTime="selectBetweenTime"
            :selectIndustryType="5"
            :positionTagId="positionTagId"
            @onIndustryChange="onIndustryChange"
          />
        </el-form-item>
      </el-form>
    </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
        <div class="regionLineDesc">
          <div class="cityTitle">{{ currentChartRegionName }}</div>
          <div
            class="regionLineDescItem"
            v-for="(item, index) in chartDescData"
            :key="index"
          >
            <div class="descTitle">
              {{ item.keyName + getMonth(item.calMonth) }}相关专业应届生平均薪酬约
            </div>
            <div class="descNum">
              <span class="rmb">￥</span>{{ item.salary }}/<span class="rmb"
                >月</span
              >
            </div>
          </div>
        </div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else>
        <!-- <el-button type="primary" size="mini" @click="handleKnowClick()">
            想要了解
          </el-button> -->
      </el-empty>
    </div>
  </div>
</template>

<script>
import { getCompanyTagSalary } from "@/api/home.js";
import IndustryCheckbox from "@/components/IndustryCheckbox/index";
export default {
  name: "workBarChart",
  components: {
    IndustryCheckbox,
  },
  props: {
    positionTagId: {
      type: String,
      default: "",
    },
  },
  watch: {
    positionTagId: {
      handler(val) {
        if (val) {
          this.positionTagId = String(val);
          this.selectedIndustryList = []; //初始化
          this.getDefaultData();
        } else {
          this.chartDataIsNotEmpty = false;
        }
      },
      // immediate: true,
    },
  },
  data() {
    return {
      resData: [],
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      chartData: {},
      selectBetweenTime: [],
      pickerMinDate: "",
      firstDayofLastMonth: "",
      pickerOptions: {
        showClear: false,
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 6 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
      },
      average: "",
      selectedRegionList: [],
      regionLineDescAvg: "",
      isSetDefaultTime: false,
      isSetDefaultRegion: true,
      currentChartRegionName: "全国",
      chartDescData: [],
      listLoading: false,
    };
  },
  computed: {
    isLabelShow() {
      return this.$store.state.chart.isLabelShow;
    },
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;
  },
  mounted() {
    this.getDefaultData();
    if (!this.positionTagId) {
      this.chartDataIsNotEmpty = false;
    }
  },
  methods: {
    getDefaultData() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let newYear = 0;
      let newMonth = 0;
      let newDateArr = [];
      for (let i = 0; i < 7; i++) {
        //这里是获取前六个月,所以循环6次,根据需要修改
        if (month - i < 1) {
          //这里的判断是如果当前月份往前推到了去年  需要做的处理
          newYear = year - 1;
          newMonth =
            month - i + 12 >= 10 ? month - i + 12 : "0" + (month - i + 12);
          newDateArr.push(newYear + "-" + newMonth + "-" + "01"); //这里拼接格式化,在时间中间加了个-,根据实际需求来
        } else {
          newMonth = month - i >= 10 ? month - i : "0" + (month - i); //这里是对月份小于10做加前面加0处理
          newDateArr.push(year + "-" + newMonth + "-" + "01");
        }
      }
      //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
      const end = newDateArr[1];
      const start = newDateArr[6];
      this.selectBetweenTime = [start, end];
    },
    onIndustryChange(val) {
      if (val && val.length) {
        this.selectedIndustryList = [];
        val.forEach((item) => {
          this.selectedIndustryList.push(item.split("-")[0]);
        });
      } else {
        this.selectedIndustryList = [];
      }
      this.fetchData();
    },
    getMonth(calMonth) {
      // 解析日期字符串
      const date = new Date(calMonth);

      // 获取月份和年份
      const month = date.getMonth() + 1; // getMonth() 返回 0-11，所以需要加 1
      // 格式化为“6月2024”格式
      return `${month}月`;
    },
    getWorkYearClass(index) {
      const obj = {
        0: "pink",
        1: "green",
        2: "blue",
        3: "skyBlue",
        4: "brown",
      };
      return obj[index];
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        positionTagId: this.positionTagId,
        keyType: "1",
      };
      if (this.selectBetweenTime) {
        params.startTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
      }
      params.keyId = this.selectedIndustryList[0];
      // if (params.keyId === "YL0000") {
      //   params.keyId = "100000"; //全部行业
      // }
      getCompanyTagSalary(params)
        .then((response) => {
          this.listLoading = false;
          if (response.code == 200) {
            // console.log("getCompanyTagSalary---------->", response);
            this.resData = response.data;
            this.chartDescData = response.data;
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
          this.listLoading = false;
        });
    },
    handleData(data) {
      // 降序
      // //console.log("handleData", data);

      // data.sort((a, b) => {
      //   return b.salaryNum - a.salaryNum;
      // });
      let dataArr = {
        calMonth: [],
        salary: [],
      };
      data.forEach((element) => {
        dataArr.calMonth.push(this.formatDate(element.calMonth));
        dataArr.salary.push(element.salary);
      });
      // console.log("----------->", dataArr);
      return dataArr;
    },
    formatDate(dateString) {
      // 解析日期字符串
      const date = new Date(dateString);

      // 获取月份和年份
      const month = date.getMonth() + 1; // getMonth() 返回 0-11，所以需要加 1
      const year = date.getFullYear();

      // 格式化为“6月2024”格式
      return `${month}月${year}`;
    },
    init() {
      if (!this.$refs["line_echartDom"]) return;
      this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);
      let calMonth = this.chartData.calMonth,
        salary = this.chartData.salary;
      let option = {
        xAxis: {
          type: "category",
          data: calMonth,
          name: "(月份)",
          interval: 0,
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split("");
                const index = array.indexOf("月");
                //在下标2处删除0个，加上回车
                array.splice(index + 1, 0, "\n\n");
                return array.join("");
              } else {
                return val;
              }
            },
            color: "#8193B2",
            fontSize: "12px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            lineHeight: 30, //标题行高
            color: "#8193B2",
            verticalAlign: "top", //标题位置
            padding: [-2, 0, 0, 0], // 上右下左与原位置距离
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            lineStyle: {
              color: "#000000",
            },
          },
          backgroundColor: "#FB9A3E",
          borderColor: "#FB9A3E",
          textStyle: {
            color: "#fff",
          },
          formatter: (params) => {
            const content = params[0];
            return `平均薪资：${content.value}元/月`;
          },
          // position: ["50%", 0],
        },
        grid: {
          top: "50",
          left: "50",
          right: "80",
          // right: "4%",
          bottom: "50",
          // containLabel: true,
        },
        yAxis: {
          type: "value",
          // scale: true,
          name: "(数量 个)",
          axisLabel: {
            color: "#8193B2",
            fontSize: "12px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            padding: [0, 45, 10, 0], // 上右下左与原位置距离

            color: "#8193B2",
          },
        },
        series: [
          {
            data: salary,
            type: "bar",
            showBackground: false,
            barWidth: "18px",
            label: {
              show: this.isLabelShow,
              position: "top",
            },
            itemStyle: {
              normal: {
                color: this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    //只要修改前四个参数就ok
                    offset: 0,
                    color: "#FFC48C",
                  }, //柱图渐变色
                  {
                    offset: 1,
                    color: "#BCF3C6",
                  },
                ]),
                borderRadius: [4, 4, 0, 0],
              },
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#FF9735", // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#77D98A", // 100% 处的颜色
                    },
                  ],
                  global: false, // 缺省为 false
                },
              },
            },
          },
        ],
      };
      this.myChart.on("mouseover", (params) => {
        this.$emit("update:hoverValue", params.value);
        this.$emit("update:hoverName", params.name);
      });
      option && this.myChart.setOption(option);
      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      document.addEventListener("fullscreenchange", function () {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: 1,
      });
      this.$emit("update:hoverValue", this.chartData.salary[1]);
      this.$emit("update:hoverName", this.chartData.city[1]);
    },
    onWorkYearChange(val) {
      this.fetchData();
    },
    handleDateChange(val) {
      if (this.isSetDefaultTime) {
        this.isSetDefaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      this.fetchData();
    },
    onRegionChange(val) {
      // //console.log("workLineChart------onRegionChange----------->",val);
      this.currentChartRegionName = val[0].split("-")[1];
      this.selectedRegionList = [];
      val.forEach((item) => {
        this.selectedRegionList.push(item.split("-")[0]);
      });
      if (this.isSetDefaultRegion) {
        this.isSetDefaultRegion = false;
        return;
      }
      this.fetchData();
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo")); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = "";
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: "44",
        layerName: "工作年限薪酬分布",
        personId: localStorage.getItem("personId") || "",
        oaId: oaId,
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success("已成功提交");
        } else {
          this.$message.error(res.status_desc);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.pink {
  font-weight: bold;
}
.green {
  font-weight: bold;
}
.blue {
  font-weight: bold;
}
.skyBlue {
  font-weight: bold;
}
.brown {
  font-weight: bold;
}
.content {
  margin: 0px 12px;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  margin-top: 16px;
  color: #222;
  font-weight: bold;
  margin-bottom: 22px;
  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.chartMain {
  display: flex;
  width: 100%;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
  // align-items: center;
  .h100 {
    flex: 0.65;
  }
  .regionLineDesc {
    /* // margin-left: 45px; */
    display: flex;
    flex: 0.35;
    flex-wrap: wrap;
    /* width: 400px; */
    justify-content: space-between;
    // align-content: center;
    margin: 10px 10px 10px 10px;
    .cityTitle {
      display: flex;
      width: 100%;
      margin: 10px auto;
      font-size: 18px;
      font-weight: bold;
      color: #222;
      align-items: center;
    }
    .cityTitle::before {
      content: "";
      display: inline-block;
      width: 8px;
      height: 8px;
      top: 50%;
      border-radius: 50%;
      background-color: #fb9a3e;
      margin-right: 8px;
    }
    .regionLineDescItem {
      margin: 10px 0px;
      width: 48%;
    }
    .descTitle {
      color: #555;
      font-size: 15px;
    }
    .descNum {
      display: flex;
      align-items: baseline;
      color: #1b78ff;
      font-size: 24px;
      font-weight: bold;
      margin-top: 22px;
      font-family: D-DIN-PRO-500-Medium;
    }
    .rmb {
      font-size: 18px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  margin-left: 5vw;
  .regionLineDescItem {
    margin-top: 25px;
  }
  .regionLineDescItem:first-of-type {
    margin-top: 0;
  }
}
.descTitle {
  color: #555;
  font-size: 16px;
  span {
  }
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 20px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-600-SemiBold;
}

.rmb {
  font-size: 18px;
}
.h100 {
  width: 100%;
  // height: 20vw;
  min-width: 615px;
  min-height: 280px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  line-height: 22px;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 内容超出容器部分隐藏 */
  text-overflow: ellipsis; /* 使用省略号表示被截断的内容 */
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
  margin-top: 10px;
}
.search-container {
  display: flex;
  align-items: center;
}
</style>
